﻿using System;
using System.Windows.Forms;

namespace SingletonEvents
{
	public partial class ChildForm : Form
	{
		#region Fields

		private readonly int number;
		private readonly bool unsubscribeFromEvents;
		private bool disposed;

		#endregion Fields

		#region Constructors

		public ChildForm(int number, bool unsubscribeFromEvents)
		{
      InitializeComponent();

			this.number = number;
			this.unsubscribeFromEvents = unsubscribeFromEvents;

			Closing += ThisClosingEventHandler;
			Disposed += ThisDisposedEventHandler;
			Singleton.Instance.EventTriggered  += SingletonEventTriggeredEventsHandler;
		}

		#endregion Constructors

		#region Event handlers

		private void SingletonEventTriggeredEventsHandler(object sender, EventTriggeredEventsArgs e)
		{
			if (disposed)
			{
				string errorText = string.Format("Form #{0} has been already disposed", number);
				throw new InvalidOperationException(errorText);
			}

			MessageLabel.Text = string.Format("Form #{0} is active", e.ActiveChildFormNumber);
		}

		private void ThisClosingEventHandler(object sender, EventArgs e)
		{
			if (unsubscribeFromEvents)
			{
				Singleton.Instance.EventTriggered -= SingletonEventTriggeredEventsHandler;
			}
		}

		private void ThisDisposedEventHandler(object sender, EventArgs e)
		{
			disposed = true;
		}

		#endregion Event handlers
	}
}
